package com.xy.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.Part;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:图片上传工具
 * Date: 2018-01-17
 * Time: 17:05
 */
public class UpPictureUtil {

  public Map<String, String> upPicture(Part part) throws IOException {

        String uid = UUID.randomUUID().toString();
        String address = uid.replaceAll("\\-", "");

        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentDisposition(address);
        meta.setContentType(part.getContentType());

        //获取类型
        String type = meta.getContentType();
        InputStream ip = part.getInputStream();
        BufferedImage img = javax.imageio.ImageIO.read(ip);
        //获取宽高
        int w = img.getWidth();
        int h = img.getHeight();
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream im = ImageIO.createImageOutputStream(bs);
        ImageIO.write(img, "jpg", im);
        InputStream is = new ByteArrayInputStream(bs.toByteArray());
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAIIi26zW53630H";
        String accessKeySecret = "OZrHArY8HHXks232UIhnNNv36zDafW";

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        int a;
        try {
            ossClient.putObject("trunkphoto", address, is, meta);
            a = 1;
        } catch (Exception e) {
            // TODO: handle exception
            a = 0;
        }
        is.close();
        bs.close();
        ossClient.shutdown();
        String width = String.valueOf(w);
        String height = String.valueOf(h);
        String url = "http://trunkphoto.oss-cn-beijing.aliyuncs.com/" + address;
        Map<String, String> map = new HashMap<>();
        Map<String, String> map1 = new HashMap<>();
        map.put("width", width);
        map.put("height", height);
        map.put("url", url);
        map.put("result","1");
        map1.put("result", "0");
        if (a == 1) {
            return map;
        } else {
            return map1;
        }


    }



}
